package com.codewsq.exer.syn2;

/*
 * 实现Runnable的方式创建多线程,并完成三个窗口售票100张的需求
 * */
class WindowTicket implements Runnable {

    private int ticket = 100;
    private Object object = new Object();

    @Override
    public void run() {
        while (true) {
            this.show();
            if (ticket <= 0) {
                break;
            }
        }
    }
    /*
    * 同步方法：和同步代码块一样，都是synchronized关键字，只不过是在方法返回类型之前加上
    * 同步方法同样有 同步监视器（锁），只不过默认是当前对象 this
    * 实现Runnable接口的方式创建线程，因为是天然的多个线程共享同一个对象，所以可以直接添加synchronized关键字
    * */
    private synchronized void show() {
        if (ticket > 0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + ":" + ticket);
            ticket--;
        }
    }
}


public class TicketSalesToRunnable {
    public static void main(String[] args) {
        WindowTicket ticket = new WindowTicket();
        Thread t1 = new Thread(ticket);
        Thread t2 = new Thread(ticket);
        Thread t3 = new Thread(ticket);

        t1.setName("窗口一");
        t2.setName("窗口二");
        t3.setName("窗口三");

        t1.start();
        t2.start();
        t3.start();
    }
}
